<!--  -->
<template>
  <div class="app-main-container">
    <div class="app-main-title">
      {{ managerName }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> {{ $t("message.fhsyy") }}
      </div>
    </div>
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        :rules="rules"
        label-width="auto"
        label-suffix="："
      >
        <div class="property-title">{{ $t("message.spxx") }}</div>
        <el-form-item :label="$t('message.sptp')">
          <transition name="fade">
            <Cropper
              v-if="dialogCropperVisible"
              :option-img="optionImg"
              :fileinfo="fileinfo"
              use-type="GOODS_IMG"
              :fixed-number="[32, 32]"
              @formSubmit="cropperSubmit"
              @formClose="cropperClose"
            />
          </transition>
          <div class="df_ac">
            <el-upload
              class="device-uploader"
              accept=".jpg,.png"
              :auto-upload="false"
              :action="uploadFileUrl"
              :data="uploadParam"
              :show-file-list="false"
              :on-change="addFileChange"
            >
              <i class="el-icon-plus uploader-icon" />
              <div
                v-show="param.showPoster"
                class="file"
                :style="'background-image: url(' + param.showPoster + ')'"
              >
                <div class="delete">
                  <i
                    class="el-icon-delete icon"
                    @click.stop="deleteDeviceConfigAddImage"
                  />
                </div>
              </div>
            </el-upload>
            <div class="placeholder9">
              <div>{{ $t("message.jycc") }}：{{ "100px X 100px" }}</div>
              <div>
                {{ $t("message.zctpsm") }}
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.lbt')">
          <el-upload
            ref="bannerRef"
            :action="uploadFileUrl"
            accept=".jpg,.png,.webp"
            list-type="picture-card"
            :file-list="param.ImageList"
            :limit="6"
            multiple
            :on-success="filesUploadSuccess"
            :on-remove="filesUploadRemove"
            name="file"
            :data="uploadParam"
          >
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">
              {{ $t("message.zctpsm") }},{{ $t("message.sxz6") }}
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('message.spmc')" prop="name">
          <el-input
            v-model="param.name"
            :placeholder="$t('message.qsr') + $t('message.spmc')"
            maxlength="50"
            class="w400"
          />
        </el-form-item>
        <el-form-item
          :label="$t('message.spfl')"
          class="select-style"
          prop="firstClassifyId"
        >
          <el-select
            v-model="param.firstClassifyId"
            :placeholder="$t('message.qxz') + $t('message.spfl')"
            class="w200"
            @change="changeClassId"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-if="param.firstClassifyId"
            v-model="param.classifyId"
            :placeholder="$t('message.spejfl')"
            class="w200"
            clearable
          >
            <el-option
              v-for="item in typeListChild"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.txm')">
          <el-input
            v-model="param.barCode"
            :placeholder="$t('message.qsr') + $t('message.sptxm')"
            maxlength="50"
            class="w400"
          />
          <el-button type="primary" class="ml20" @click="createCode">{{
            $t("message.shechen")
          }}</el-button>
        </el-form-item>
        <el-form-item :label="$t('message.spkc')" prop="stock">
          <el-input
            v-model="param.stock"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            :placeholder="$t('message.qsr') + $t('message.spkc')"
            class="w400"
            maxlength="10"
          />
        </el-form-item>
        <el-form-item :label="$t('message.xsj')" prop="price">
          <el-input
            v-model="param.price"
            oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            :placeholder="$t('message.qsr') + $t('message.xsj')"
            maxlength="10"
            class="w400"
          />
        </el-form-item>
        <el-form-item :label="$t('message.hxj')" prop="originalPrice">
          <el-input
            v-model="param.originalPrice"
            oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            :placeholder="$t('message.qsr') + $t('message.hxj')"
            maxlength="10"
            class="w400"
          />
        </el-form-item>
        <el-form-item :label="$t('message.spbq')">
          <el-input
            v-model="param.label"
            :placeholder="$t('message.qsr')"
            class="w400"
          />
        </el-form-item>
        <el-form-item :label="$t('message.csxl')">
          <el-input
            v-model="param.virtualNum"
            :placeholder="$t('message.qsr')"
            oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
            class="w400"
          />
        </el-form-item>
        <!-- <el-form-item :label="$t('message.spgg')" class="select-style">
          <el-select v-model="param.goodsSkuIds" multiple :placeholder="$t('message.qxz') + $t('message.spfl')">
            <el-option
              v-for="item in skuNameList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item class="form-inline" :label="$t('message.sfsj')">
          <el-switch v-model="isOn" />
        </el-form-item>
        <el-form-item
          :label="$t('message.zklx')"
          class="select-style"
          prop="discountType"
        >
          <el-select
            v-model="param.discountType"
            :placeholder="$t('message.qxz') + $t('message.zklx')"
            class="w400"
          >
            <el-option
              v-for="item in discountType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <div
          v-if="param.discountType == '1'"
          style="display: flex; flex-wrap: wrap"
        >
          <el-form-item
            v-for="vip in vipTypeList"
            :key="vip.id"
            align="center"
            :label="vip.cardName"
            style="width: 50%"
            :prop="`discountMap.${vip.id}`"
            :rules="{
              required: true,
              message: $t('message.qsr') + $t('message.hyzk'),
              trigger: 'blur',
            }"
          >
            <el-input
              v-model="param.discountMap[vip.id]"
              onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
              oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
              type="text"
              :placeholder="
                $t('message.qsr') +
                $t('message.hyzk') +
                '(' +
                $t('message.bllwxs') +
                ')'
              "
              maxlength="50"
            />
          </el-form-item>
        </div>
        <el-form-item :label="$t('message.spxq')">
          <div class="secondColor">
            {{ $t("message.tpbnfz") }}
          </div>
          <!-- <WangEditor
            ref="myTextEditor"
            :value="param.info"
            @input="(e) => $set(param, 'info', e)"
          /> -->
          <quill-editor
            ref="myTextEditor"
            v-model="param.info"
            :placeholder="$t('message.qsrnr')"
            class="myQuillEditor"
            :options="quillOption"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-preventReClick
            :loading="subLoading"
            type="primary"
            @click="onSubmit()"
            >{{ $t("message.tj") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import Cropper from "@/components/cropper";
// import WangEditor from '@/components/quillOption'
import { quillEditor } from "vue-quill-editor";
import quillConfig from "@/api/sc.js";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import {
  uploadFile,
  goodsClassifyListVenue,
  cardList,
  goodsSave,
  goodsEditQuery,
  goodsEditSave,
  goodsSkuNameList,
} from "@/api";
export default {
  name: "GoodsAdd",
  components: {
    Cropper,
    quillEditor,
  },
  data() {
    return {
      quillOption: quillConfig,
      subLoading: false,
      listLoading: true,
      dialogCropperVisible: false,
      optionImg: "",
      files: {},
      fileinfo: {},
      swiperOptions: {
        slidesPerView: "auto",
        pagination: {
          el: ".swiper-pagination",
        },
      },
      managerName: "",
      logoList: [],
      uploadParam: {
        folder: "GOODS_IMG",
      },
      typeList: [],
      typeListChild: [],
      vipTypeList: [],
      uploadFileUrl: uploadFile,
      discountType: [
        { value: "0", label: this.$t("message.mrzk") },
        { value: "1", label: this.$t("message.zdyzk") },
      ],
      isOn: false,
      param: {
        discountType: "0",
        venueId: sessionStorage.getItem("venueId"),
        discountMap: {},
        // goodsSkuIds: []
      },
      rules: {
        picture: [
          {
            required: true,
            message: this.$t("message.qsc") + this.$t("message.sptp"),
            trigger: "blur",
          },
        ],
        imgList: [
          {
            type: "array",
            required: true,
            message: this.$t("message.qsc") + this.$t("message.lbtp"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.spmc"),
            trigger: "blur",
          },
        ],
        barCode: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.sptxm"),
            trigger: "blur",
          },
        ],
        firstClassifyId: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.spfl"),
            trigger: "change",
          },
        ],
        stock: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.spkc"),
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.spjg"),
            trigger: "blur",
          },
        ],
        info: [
          {
            required: true,
            message: this.$t("message.qsr") + this.$t("message.spjs"),
            trigger: "blur",
          },
        ],
        discountType: [
          {
            required: true,
            message: this.$t("message.qxz") + this.$t("message.zklx"),
            trigger: "change",
          },
        ],
      },
      skuNameList: [],
    };
  },
  beforeRouteEnter(to, from, next) {
    // to.meta.title = to.query.id ? this.$t('message.bjsp') : this.$t('message.xzsp')
    next();
  },

  created() {
    if (this.$route.query.id) {
      this.managerName = this.$t("message.bjsp");
      this.getClassifyList();
      this.getGoodsDetailInfo(this.$route.query.id);
    } else {
      this.managerName = this.$t("message.xzsp");
      this.getClassifyList();
      this.getCardList();
    }
    goodsSkuNameList({
      param: {
        venueId: sessionStorage.getItem("venueId"),
        saleType: 0,
      },
    }).then((res) => {
      // console.log(res);
      if (res.errorCode === "000000") {
        this.skuNameList = res.recordList;
      }
    });
  },
  methods: {
    changeClassId(id) {
      const { typeList } = this;
      const findItem = typeList.find((i) => i.id === id);
      this.typeListChild = findItem.item || [];
      this.$set(this.param, "classifyId", "");
    },
    createCode() {
      const str = new Date().getTime();
      this.$set(this.param, "barCode", str);
    },
    getGoodsDetailInfo(id) {
      Promise.all([
        // 获取卡类型列表
        cardList({
          param: {
            cardName: null,
            isnormal: null,
            channel: null,
          },
        }),
        goodsEditQuery({
          param: {
            id,
          },
        }),
      ]).then((res) => {
        this.vipTypeList = res[0].recordList;
        const obj = res[1].record;
        this.param = obj;
        this.$set(this.param, "showPoster", res[1].record.showPicture);
        this.$set(this.param, "poster", res[1].record.picture);
        this.showPictures();
        this.param.picture = res[1].record.picture;
        this.isOn = this.param.status === "1";
        // console.log(this.param.goodsSkuIds.length);
        // this.param.goodsSkuIds = this.param.goodsSkuIds.length ? this.param.goodsSkuIds.split(',') : []
        // console.log(this.param);
        const discountmap = res[1].record.discountMap;
        setTimeout(() => {
          const id = res[1].record.firstClassifyId;
          const { typeList } = this;
          const findItem = typeList.find((i) => i.id === id);
          this.typeListChild = findItem.item || [];
        }, 1000);
        if (res[1].record.discountType === "0") {
          this.$set(this.param, "discountMap", {});
        } else {
          this.$set(this.param, "discountMap", discountmap);
        }
      });
    },
    showPictures() {
      const imageList = [];
      const showpicture = this.param.showImgList;
      const pictures = this.param.imgList;
      showpicture.forEach((item, index) => {
        imageList.push({
          url: showpicture[index],
          response: {
            insertUrl: pictures[index],
            showUrl: showpicture[index],
          },
        });
      });
      // this.filters.venueImageList = pictures
      this.$set(this.param, "ImageList", imageList);
    },
    getCardList() {
      // 获取卡类型列表
      cardList({})
        .then((res) => {
          if (res.errorCode === "000000") {
            this.vipTypeList = res.recordList;
            const map = res.recordList;
            map.map((item) => {
              item.set("creator", "");
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 场馆端商品分类列表
    getClassifyList() {
      goodsClassifyListVenue({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          saleType: 0,
        },
      })
        .then((res) => {
          this.listLoading = false;
          if (res.errorCode !== "000000") return;
          this.typeList = res.recordList;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    // showGoodsImage() {
    //   const ImageList = []
    //   if (this.param.showPicture) {
    //     ImageList.push({
    //       url: this.param.showPicture,
    //       response: {
    //         insertUrl: this.param.picture,
    //         showUrl: this.param.showPicture
    //       }
    //     })
    //     this.logoList = [this.param.picture]
    //   }
    //   this.logoList = ImageList
    // },
    onlyDecimal(that, maxLen) {
      var reg = /^(([1-9][0-9]*)|(([0].\d{0,2}|[1-9][0-9]*.\d{0,2})))$/;
      if (that.value.length === 1) {
        that.value = that.value.replace(/[^0-9]/g, "");
      } else {
        if (!reg.test(that.value)) {
          that.value = "";
        }
      }

      if (
        !(typeof maxLen === "undefined" || maxLen === "" || maxLen == null) &&
        that.value.length > maxLen
      ) {
        var val = that.value;
        that.value = val.toString().substring(0, parseInt(maxLen));
      }
    },
    filesUploadSuccess(response, file, fileList) {
      if (response && response.names && response.names.length > 0) {
        const imgList = [];
        fileList.forEach((image) => {
          imgList.push(image.response.insertUrl);
        });
        this.$set(this.param, "imgList", imgList);
        // this.param.imgList = fileList
        this.$refs.form.clearValidate();
      } else {
        this.$message.info(response.msg);
        this.$set(this.param, "imgList", []);
        this.$set(this.param, "ImageList", []);
        this.$refs.form.clearValidate();
      }
    },
    // 场馆图片移除
    filesUploadRemove(file, fileList) {
      const imgList = [];
      if (fileList.length > 0) {
        fileList.forEach((obj) => {
          imgList.push(obj.response.insertUrl);
        });
      }
      this.$set(this.param, "imgList", imgList);
      // console.log(this.filters.ImageList)
    },
    // 商品图片上传成功
    uploadSuccess(response, file, fileList) {
      this.$set(this.param, "picture", fileList[0].response.insertUrl);
      this.$refs.form.clearValidate();
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw;
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw);
        this.fileinfo = file.raw;
        this.dialogCropperVisible = true;
      });
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, "showPoster", config.showUrl);
        this.$set(this.param, "poster", config.insertUrl);
        this.$set(this.param, "picture", config.insertUrl);
        this.$refs.form.clearValidate();
        this.fileinfo = config;
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false;
      } else {
        this.$message.error(config.msg || this.$t("message.scsb"));
        this.$refs.form.clearValidate();
        this.dialogCropperVisible = false;
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false;
    },
    // 商品图片移除
    deleteDeviceConfigAddImage(file, fileList) {
      this.$set(this.param, "showPoster", "");
      this.$set(this.param, "poster", "");
      this.param.picture = "";
    },
    onSubmit() {
      const param = { ...this.param };
      param.status = this.isOn ? "1" : "0";
      param.venueId = sessionStorage.getItem("venueId");
      param.saleType = 0;
      // param.goodsSkuIds = this.param.goodsSkuIds.join(',') || ''
      if (this.$route.query.id) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true;
            goodsEditSave({
              param,
            })
              .then((res) => {
                if (res.errorCode !== "000000") return;
                this.subLoading = false;
                this.$message.success(this.$t("message.editcg"));
                // this.$router.go(-1)
                this.$router.replace(
                  `/goodsmanager/managerList?renovate=1&page=${this.$route.query.page}&showChildId=${this.$route.query.showChildId}`
                );
              })
              .catch(() => {
                this.subLoading = false;
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.subLoading = true;
            goodsSave({
              param,
            })
              .then((res) => {
                if (res.errorCode !== "000000") return;
                this.subLoading = false;
                this.$message.success(this.$t("message.addcg"));
                this.$router.go(-1);
              })
              .catch(() => {
                this.subLoading = false;
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
    // 返回上一页
    goBack() {
      this.$router.replace("/goodsmanager/managerList");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
</style>
